-- Version : 0.30

apidir=shell.resolve("api")
tmpdir=shell.resolve("tmp")

-- For editing out of Minecraft I use an editor that needs an extension (.lua) to get syntax highlighting working
-- To save the ballache of copying and renaming it to a non-extensioned file, I just do that here in the script..
fs.delete(tmpdir.."/brum")
fs.delete(tmpdir.."/logger")
fs.copy(apidir.."/brum.lua",tmpdir.."/brum")
fs.copy(apidir.."/logger.lua",tmpdir.."/logger")

os.unloadAPI(tmpdir.."/brum")
os.loadAPI(tmpdir.."/brum")
os.unloadAPI(tmpdir.."/logger")
os.loadAPI(tmpdir.."/logger")

-- Some global flags to control turtle behaviour
local quitflag = false -- Used to break out of the main routine if there is an error
local completed = false -- Used to signal that the turtle has completed what was asked of it

-- How many inventory slots does the turtle have?
invSlots = 16

-- Refuel if turtle's remaining number of moves are lower than...
brum.setRefuelLevel(100)

-- For rednet message broadcasting to base logging console...
consoleID=1 -- Send messages back to console ID 1

local tArgs = { ... }
term.clear()
term.setCursorPos(1,1)
rednet.open("right") -- Open wireless modem on RH side for communication to base console


------------------
-- MAIN ROUTINE --
------------------

local squaresize = 5
local mineheight = 100
logger.setDebug()

if #tArgs > 0 then
  if tArgs[1] == "help" or tArgs[1] == "Help" then
    print("Usage: danmine [squaresize] [height from bedrock]")
    print()
    print("For example, 'danmine 5 40' would mine a 5x5 grid, starting from the bedrock")
    print("and moving up for 40 blocks maximum. It will not mine above that.")
    print()
    print("If ommitted, [squaresize] defaults to 5")
    print("If ommitted, [height from bedrock] defaults to 100")
    quitflag = true
  elseif #tArgs == 2 then
  	squaresize=tonumber(tArgs[1])
  	mineheight=tonumber(tArgs[2])
	elseif #tArgs == 1 then
	  squaresize=tonumber(tArgs[1])
  end
end

local refuelLevel = brum.getRefuelLevel()
local currentFuel = brum.fuelcheck()

if currentFuel==0 then
	-- We have no fuel in stock
	logger.crit("No initial fuel")
	error("No initial fuel")
elseif (currentFuel<refuelLevel) then
	logger.crit("Fuel level < "..refuelLevel.." - please provide more")
	error("Low initial fuel - please provide more")
end

logger.info("Square size = "..squaresize.."\nMine ceiling = "..mineheight)

local maxDepth = 0 -- Keep record of maximum depth reached...
local down = 0 -- level mined from start depth down (delta)
local offsetX = 0
local offsetZ = 0

-- Mine straight down to bedrock...
logger.info("Moving to bedrock layer...")
while brum.moveDown() do
	maxDepth=maxDepth-1
end
logger.debug("Bedrock located at depth "..math.abs(maxDepth))
down = maxDepth

while (down<maxDepth+mineheight and (not completed)) do

	local areaResult = false
	local errorReason = ""
	
	brum.orientMe(0)
	-- Dig this level's square
	areaResult,errorReason,offsetX,offsetZ = brum.mineRectangle(offsetX,offsetZ,squaresize,squaresize)

	-- While we've not dug the whole square out, keep attempting it, unfilling at the surface as needed
	if (not areaResult) or (string.len(errorReason)>0) then
		logger.info("Area not finished : ["..errorReason.."]")
		-- We didn't mine the whole square because of blockage, fuel or we're full... verify what to do...
		if (errorReason=="full" or errorReason=="fuel") then
			logger.info("Return home, dump load & refuel")
			local result, reason
			result, reason = brum.returnXYZ(0,0,0)
			if (not result) then
				logger.crit("Failed to return home - "..reason)
				areaResult=true -- to break out
				errorReason=reason
			end
		  brum.orientMe(2)
		  brum.dumpLoad()
	  	brum.getFuel()
		  logger.info("Resume at "..offsetX..","..offsetZ)	
		else
			--Must be blocked while processing the area - so abort the area
			logger.info("Abort this square")
			result, reason = brum.returnXYZ(0,down,0)
			areaResult=true -- to break out of while loop
		end	
	else
		logger.info("Square complete")
		brum.returnXYZ(0,down,0)
		areaResult=true
		errorReason=""
  end

	down=down+1
	result, reason = brum.moveY(down)
	if not result then 
		-- Something off, if we can't move back up the mineshaft then something is in the way :-S
		logger.crit("Failed to move up a level - aborting") 
		completed=true
	end
	
	-- If we've reached our mine ceiling then we're done, set the flag to exit out
	if (down==maxDepth+mineheight) then
		completed=true
	end
	
end
logger.info("Mine complete")
brum.returnXYZ(0,0,0)
-- Spit it out!
brum.orientMe(2)
brum.dumpLoad()
brum.orientMe(0)
logger.debug("Finished")

rednet.close("right")
